/** @odoo-module **/
import init_grid_options from '../ag_grid/gridOptions.js'


const {
    markup,
    Component,
    onWillStart,
    useEnv,
    useSubEnv,
    useChildSubEnv,
    useRef,
    useState,
    mount,
    xml,
    whenReady,
    onMounted,
    onError,
    loadFile,
    onWillUpdateProps,
    useEffect,
    useComponent
} = owl;

class ImportModal extends Component {
    static template = xml`
         <div class="modal fade" id="ImportModal">
  <div class="modal-dialog modal-fullscreen">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5">导入到当前模板</h1>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
        <div class="modal-body">
            <div class="d-flex flex-column" style="height:100%">
                <p style="margin-bottom: 5px;">从EXCEL中复制(Ctrl+C)总菜单,粘贴(Ctrl+V)到本表格，然后点击 【确定】 保存到模板中。</p>
                <p class="text-success">输入规范：<t t-esc="state.tips"/></p>
                <div t-ref="ImportGrid" style="width: 100%;" class="ag-theme-balham myGrid"/>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" t-on-click.stop="handleConfirm">确定</button>
      </div>
    </div>
  </div>
</div>`;
    static props = {
        is_open: {type: Boolean},
        data:{type: Object}
    };

    setup() {
        this.ImportGrid_ref = useRef('ImportGrid');
        this.defaultRowData = [];
        for (let i = 0; i < 10; i++) {
            this.defaultRowData.push({
                id:i+1
            });
        }
        this.addMaxId = 10;
        this.rowData = JSON.parse(JSON.stringify(this.defaultRowData));
        this.values = {
            dinner_type:[],
            dish_top_category_name:[],
            sales_type:['快餐','特色']
        };
        this.state = useState({
            tips:'',
            redrawRowsFlag:true
        });

        onMounted(() => {
            let _this = this;
            this.Modal = new bootstrap.Modal('#ImportModal', {});

            document.getElementById('ImportModal').addEventListener('hidden.bs.modal', event => {
                _this.env.closeImportModal();
            });

            this.ImportGridOptions = Object.assign({}, init_grid_options(), {
                rowData: [],
                columnDefs: [],
                context: {
                    owl_widget: _this
                },
                getContextMenuItems: (e) => {
                    return [];
                },
                processDataFromClipboard:(params)=>{
                    return _this.processDataFromClipboard(params)
                },
                // processCellFromClipboard:(params) => {
                //     return _this.processCellFromClipboard(params)
                // },
                onPasteEnd:(params)=>{
                    return _this.onPasteEnd(params);
                },
                onCellValueChanged:(params)=>{
                    _this.redrawRows();
                    // _this.ImportGridOptions.api.refreshCells({force: true});
                    // return _this.onCellValueChanged(params);
                }
            });

            this.ImportGrid = new agGrid.Grid(this.ImportGrid_ref.el, this.ImportGridOptions);

        })

        onWillUpdateProps(nextProps => {
            // console.log(nextProps);
            if (nextProps.is_open) {
                return this.open(nextProps.data);
            }
        });

        this.handleConfirm = _.debounce(this.confirm,300);
    }
    redrawRows(){
        if(!this.state.redrawRowsFlag){
            return;
        }
        this.state.redrawRowsFlag = false;
        setTimeout(()=>{
            this.ImportGridOptions.api.redrawRows();
            this.state.redrawRowsFlag = true;
        },1000)
    }
    processDataFromClipboard(params) {
        const data = [...params.data];
        const emptyLastRow =
            data[data.length - 1][0] === '' && data[data.length - 1].length === 1;

        if (emptyLastRow) {
            data.splice(data.length - 1, 1);
        }

        const lastIndex = params.api.getModel().getRowCount() - 1;
        const focusedCell = params.api.getFocusedCell();
        const focusedIndex = focusedCell.rowIndex;

        if (focusedIndex + data.length - 1 > lastIndex) {
            const resultLastIndex = focusedIndex + (data.length - 1);
            const numRowsToAdd = resultLastIndex - lastIndex;

            const rowsToAdd = [];
            for (let i = 0; i < numRowsToAdd; i++) {
                const index = data.length - 1;
                const row = data.slice(index, index + 1)[0];

                // Create row object
                const rowObject = {};
                let currentColumn = focusedCell.column;
                row.forEach((item) => {
                    if (!currentColumn) {
                        return;
                    }
                    rowObject[currentColumn.colDef.field] = item;
                    currentColumn = params.columnApi.getDisplayedColAfter(currentColumn);
                });
                this.addMaxId++;
                rowObject.id = this.addMaxId;
                rowsToAdd.push(rowObject);
            }
            this.addMaxId++;
            rowsToAdd.push({
                id:this.addMaxId
            });
            params.api.applyTransaction({ add: rowsToAdd });
        }
        if (focusedIndex + data.length - 1 == lastIndex) {
            this.addMaxId++;
            params.api.applyTransaction({ add: [{
                    id:this.addMaxId
                }] });
        }

        return data;
    }

    processCellFromClipboard(params){
        if(!params.value){
            return '';
        }
        let colId = params.column.colId;
        let value = params.value+'';
        value = value.trim();
        if(colId == 'dinner_type' || colId == 'dish_top_category_name' || colId == 'sales_type'){
            if(!this.values[colId].includes(value)){
                return '';
            }
        }
        return value;
    }

    onCellValueChanged(params){
        let colId = params.column.colId;
        let node = params.node;
        if(colId == 'dish_top_category_name'){
            if(node.data.dish_top_category_name && node.data.dish_top_category_name != '特色'){
                node.setDataValue('sales_type','快餐')
            }
            if(node.data.dish_top_category_name && node.data.dish_top_category_name == '特色'){
                node.setDataValue('sales_type','特色')
            }
            if(!node.data.dish_top_category_name){
                node.setDataValue('sales_type','')
            }
        }
        this.ImportGridOptions.api.redrawRows();
        // console.log(params);
    }

    onPasteEnd(params){
        // console.log('Callback onPasteEnd:', params);
        this.update_all_sales_type();
    }

    update_all_sales_type(){
        let _this = this;
        let tese_index = this.values.dish_top_category_name.findIndex(v=>v == '特色');
        let prev_sales_type = '';
        let prev_dinner_type = '';
        this.ImportGridOptions.api.forEachNode(function (node) {
            if(node.data){
                let flag = false;
                for (let key in node.data) {
                    node.data[key] && (flag = true);
                }
                if(!flag){
                    prev_sales_type = '';
                    prev_dinner_type = '';
                    return;
                }
                let dish_top_category_name = node.data.dish_top_category_name||'';
                let dinner_type = node.data.dinner_type||'';
                let sales_type = '';
                if(!dish_top_category_name){
                    sales_type = prev_sales_type;
                }else if(dish_top_category_name == '特色'){
                    sales_type = '特色';
                }else if(prev_sales_type == '特色' && (prev_dinner_type == dinner_type || !dinner_type)){
                    let dish_top_category_index = _this.values.dish_top_category_name.findIndex(v=>v == dish_top_category_name);
                    if(dish_top_category_index == -1){
                        sales_type = '快餐';
                    }else if(dish_top_category_index < tese_index){
                        sales_type = '特色';
                    }else{
                        sales_type = '快餐';
                    }
                }else{
                    sales_type = '快餐';
                }
                node.setDataValue('sales_type',sales_type)
                prev_sales_type = sales_type;
                prev_dinner_type = dinner_type
            }else{
                prev_sales_type = '';
            }
        });
    }

    open(data) {
        let dinner_type = data.dinner_type_category.map(v=>v.name);
        let dish_top_category_name = data.dish_top_category.map(v=>v.name);
        this.values.dinner_type = dinner_type;
        this.values.dish_top_category_name = dish_top_category_name;
        this.state.tips = `餐别（${dinner_type.join('、')}），类别（${dish_top_category_name.join('、')}），快餐/特色（${this.values.sales_type.join('、')}）。`;

        // console.log(this.values);
        let defaultRowData = [];
        for (let i = 0; i < 10; i++) {
            defaultRowData.push({
                id:i+1
            });
        }
        this.addMaxId = 10;
        this.ImportGridOptions.api.setColumnDefs(this.setColumnDefs());
        this.ImportGridOptions.api.setRowData(defaultRowData);
        this.ImportGridOptions.api.redrawRows();
        this.Modal.show();
    }

    setColumnDefs(){
        let weekStr = '一二三四五六日';
        let columns = [
            {
                headerName: '餐别',
                field: 'dinner_type',
                menuTabs: [],
                width: 50,
                editable: true,
                suppressMovable: true,
                // valueParser:params => {
                //     let value = params.newValue || '';
                //     value.trim();
                //     if(params.newValue && params.context.owl_widget.values.dinner_type.includes(value)){
                //         return value
                //     }else{
                //         return ''
                //     }
                // }
                cellStyle: params => {
                    let value = params.value || '';
                    value = value.trim();
                    if (value && !params.context.owl_widget.values.dinner_type.includes(value)) {
                        return {backgroundColor: '#dc3545'};
                    }
                    return null;
                }
            },
            {
                headerName: '类别',
                field: 'dish_top_category_name',
                menuTabs: [],
                width: 50,
                editable: true,
                suppressMovable: true,
                cellStyle: params => {
                    let value = params.value || '';
                    value = value.trim();
                    if (value && !params.context.owl_widget.values.dish_top_category_name.includes(value)) {
                        return {backgroundColor: '#dc3545'};
                    }
                    return null;
                }
            },
        ];
        for (let i = 0; i < weekStr.length; i++) {
            columns.push({
                headerName: '星期'+weekStr[i],
                // field: 'day' + (i+1) + '_dish_key_name',
                field: 'day' + (i+1),
                menuTabs: [],
                flex:1,
                editable: true,
                suppressMovable: true,
            })
        };

        columns.push({
            headerName: '快餐/特色',
            field: 'sales_type',
            menuTabs: [],
            width: 100,
            editable: true,
            suppressMovable: true,
            cellStyle: params => {
                let value = params.value || '';
                value = value.trim();
                if (value && !params.context.owl_widget.values.sales_type.includes(value)) {
                    return {backgroundColor: '#dc3545'};
                }
                return null;
            }
        });
        return columns;
    }

    async confirm() {
        this.ImportGridOptions.api.stopEditing();
        let excel_stream = this.ImportGridOptions.api.getDataAsExcel();
        // return;
        let actual_data = await this.env.confirmImport(this.rowData, excel_stream);
        console.log('用 actual_data 来显示 真实的转换过的数据');
        this.env.importPlanModelWeekData(actual_data);
        this.Modal.hide();
        // console.log(this.rowData);
        // if (typeof (this.props.data.onConfirm) == 'function') {
        //     this.props.data.onConfirm();
        // }
    }
}


export {
    ImportModal
}
